package com.java.mall_imooc.controller;

import com.github.pagehelper.PageInfo;
import com.java.mall_imooc.common.enums.ProductStatusEnum;
import com.java.mall_imooc.common.enums.ResultEnum;
import com.java.mall_imooc.common.utils.PageUtils;
import com.java.mall_imooc.common.utils.R;
import com.java.mall_imooc.entity.Product;
import com.java.mall_imooc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;


/**
 * 商品表
 *
 * @author jl
 * @since 2020-03-14 23:41:10
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    /**
     * 根据categoryId查询其及子类目下的所有商品
     * 即查询同一分类下的所有商品
     */
    @GetMapping
    public R<PageInfo> getProductsByCategoryId(@RequestParam(value = "categoryId", required = false) Integer categoryId,
                                               @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                               @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        if (pageNum < 1) pageNum = 1;
        if (pageSize > 100) pageSize = 100;
        return productService.getProductsByCategoryId(categoryId, pageNum, pageSize);
    }

    /**
     * 带条件分页查询product
     */
    @GetMapping("/list")
    public R<PageUtils> list(Product product, @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        if (pageNum < 1) pageNum = 1;
        if (pageSize > 100) pageSize = 100;
        PageUtils page = productService.queryPage(product, pageNum, pageSize);

        return R.ok(page);
    }


    /**
     * 根据主键查询product
     */
    @GetMapping("/info/{id}")
    public R<Product> info(@PathVariable("id") Integer id) {
        Product product = productService.getById(id);
        if (product.getStatus().equals(ProductStatusEnum.OFF_SALE) || product.getStatus().equals(ProductStatusEnum.DELETED)) {
            return R.error(ResultEnum.PRODUCT_OFF_SALE_OR_DELETED);
        }
        return R.ok(product);
    }

    /**
     * 新增product
     */
    @PostMapping("/save")
    public R save(@RequestBody Product product) {
        productService.save(product);

        return R.ok();
    }

    /**
     * 修改product
     */
    @PutMapping("/update")
    public R update(@RequestBody Product product) {
        productService.updateById(product);

        return R.ok();
    }

    /**
     * 删除product
     */
    @DeleteMapping("/delete")
    public R delete(@RequestBody Integer[] ids) {
        productService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
